/**
 * 
 */
package com.easidea.tim.service.finance;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.easidea.tim.dao.customer.CustomerDao;
import com.easidea.tim.service.base.EmailProcessService;

/**
 * 每日客户账户对账处理，定时钟任务，每日凌晨1：00～1：30执行
 * 处理时，提取前一天的账户数据和对账数据，将二者的财务余额数据进行比对
 * 如果有异常，则发送邮件给指定管理员
 * 
 * @author Harrison
 *
 */
public class DailyCustomerAccountCheckJob {
	
	private static final Logger log = Logger.getLogger(DailyCustomerAccountCheckJob.class);
	private CustomerDao customerDao;
	private EmailProcessService emailProcessService;
	private String [] recpts; //接收人
	
	private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //日期格式化
	
	public void dailyCheckProcess(){
		boolean isFault = false; //判断开关，用于确认是否需要发送邮件
		List<Object[]> emailDatas = getFaultData();
		/*----- 提取数据 ------*/
		
		StringBuffer mailMessageBuffer = new StringBuffer("/r/n 以下数据存在账户余额与财务数据不匹配情况：/r/n/r/n" +
				"格式：客户Id,客户名,客户余额,财务明细id,期初余额,发生额,期末余额,帐目生成时间");
		if(emailDatas != null){
			isFault = true;//发送邮件开关打开
			
			for(Object[] data : emailDatas){
				if(data != null){
					mailMessageBuffer.append("/r/n ");
					mailMessageBuffer.append(data[0].toString()+", ");
					mailMessageBuffer.append(data[1].toString()+", ");
					mailMessageBuffer.append(data[2].toString()+", ");
					mailMessageBuffer.append(data[3].toString()+", ");
					mailMessageBuffer.append(data[4].toString()+", ");
					mailMessageBuffer.append(data[5].toString()+", ");
					mailMessageBuffer.append(data[6].toString()+", ");
					mailMessageBuffer.append(df.format((Date)data[7]));
				}
			}
		}
		/*------  封装邮件体 -------*/
		
		if(isFault){
			log.warn(" customer daily acount check fault, preparing sending data email ~~~ ");
			emailProcessService.sendMail(mailMessageBuffer.toString(),"Customer Account daily check failure [" + df.format(new Date()) + "]", recpts);
			log.warn(" check mail has been sent ~!");
		}
		/*------  发送邮件 -------*/
	}


	/**
	 * @return
	 */
	private List<Object[]> getFaultData() {
		final String sql = "SELECT cust.id, cust.name, cust.account_summary, li.id, li.last_amount, li.amount, li.total_amount, li.create_time" +
				" FROM tim_finance_customer_account_listing li, tim_customer_customer cust" +
				" WHERE cust.id = li.id AND li.total_amount <> cust.account_summary AND li.id IN (" +
				"	SELECT MAX(cal.id) FROM tim_finance_customer_account_listing cal" +
				"	WHERE cal.create_time >= DATE_FORMAT('now()' - INTERVAL 1 DAY,'%Y-%m-%d 00:00:00') " +
				"     AND cal.create_time <= DATE_FORMAT('now()' - INTERVAL 1 DAY,'%Y-%m-%d 23:59:59')" +
				"  	GROUP BY cal.customer_id) ";
		
		List<Object[]> emailDatas = (List<Object[]>) customerDao.getHibernateTemplate().execute(new HibernateCallback(){
			public List<Object[]> doInHibernate(Session session) throws HibernateException, SQLException {
				SQLQuery sqlQuery = session.createSQLQuery(sql);
				
				List<Object[]> resultArray = (List<Object[]>)sqlQuery.list();
				if(resultArray != null && !resultArray.isEmpty()){
					// 非空，有财务不平衡数据，开始整理邮件内容，发送邮件
					return resultArray;
				}else
					return null;
			}
		}); // end of HibernateTemplate execute
		return emailDatas;
	}


	/**
	 * @return the customerDao
	 */
	public CustomerDao getCustomerDao() {
		return customerDao;
	}


	/**
	 * @param customerDao the customerDao to set
	 */
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}


	/**
	 * @return the emailProcessService
	 */
	public EmailProcessService getEmailProcessService() {
		return emailProcessService;
	}


	/**
	 * @param emailProcessService the emailProcessService to set
	 */
	public void setEmailProcessService(EmailProcessService emailProcessService) {
		this.emailProcessService = emailProcessService;
	}


	/**
	 * @return the recpts
	 */
	public String[] getRecpts() {
		return recpts;
	}


	/**
	 * @param recpts the recpts to set
	 */
	public void setRecpts(String[] recpts) {
		this.recpts = recpts;
	}

}
